package org.finesys.system.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.finesys.common.core.constants.RestApiConfig;
import org.finesys.common.core.module.R;
import org.finesys.common.log.core.annotation.LogAnnotation;
import org.finesys.common.log.core.enums.OperateType;
import org.finesys.common.security.core.util.SecurityUtils;
import org.finesys.system.api.entity.SysMenu;
import org.finesys.system.constants.ControllerRestApiConfig;
import org.finesys.system.service.SysMenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.lang.tree.Tree;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;

@Tag(name = "菜单管理")
@RestController
@RequestMapping(ControllerRestApiConfig.MENU)
@RequiredArgsConstructor
public class SysMenuController {

    private final SysMenuService sysMenuService;

    @Operation(summary = "新增")
    @LogAnnotation(title = "新增", operateType = OperateType.INSERT)
    @PostMapping(RestApiConfig.ADD)
    @PreAuthorize("@pms.hasPermission('sys_menu_add')")
    public R<Boolean> add(@RequestBody SysMenu sysMenu) {
        return R.success(sysMenuService.saveMenu(sysMenu));
    }

    @Operation(summary = "修改")
    @LogAnnotation(title = "修改", operateType = OperateType.UPDATE)
    @PutMapping(RestApiConfig.UPDATE)
    @PreAuthorize("@pms.hasPermission('sys_menu_edit')")
    public R<Boolean> update(@RequestBody SysMenu sysMenu) {
        return R.success(sysMenuService.updateMenu(sysMenu));
    }

    @Operation(summary = "删除")
    @LogAnnotation(title = "删除", operateType = OperateType.DELETE)
    @DeleteMapping(RestApiConfig.DELETE + "/{id}")
    @PreAuthorize("@pms.hasPermission('sys_menu_del')")
    public R<Boolean> delete(@PathVariable Long id) {
        return R.success(sysMenuService.removeMenuById(id));
    }

    @Operation(summary = "根据ID查询路由信息")
    @GetMapping(RestApiConfig.GET + "/{id}")
    public R<SysMenu> getMenuById(@PathVariable Long id) {
        return R.success(sysMenuService.getById(id));
    }


    /**
     * 返回当前用户的树形菜单集合
     *
     * @param type     类型
     * @param parentId 父节点ID
     * @return 当前用户的树形菜单
     */
    @GetMapping
    public R<List<Tree<Long>>> getUserMenu(String type, Long parentId) {
        // 获取符合条件的菜单
        Set<SysMenu> all = new HashSet<>();
        SecurityUtils.getRoles().forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId)));
        return R.success(sysMenuService.filterMenu(all, type, parentId));
    }

    /**
     * 返回树形菜单集合
     *
     * @param parentId 父节点ID
     * @param menuName 菜单名称
     * @return 树形菜单
     */
    @GetMapping(value = RestApiConfig.TREE)
    public R<List<Tree<Long>>> getTree(Long parentId, String menuName, String type) {
        return R.success(sysMenuService.treeMenu(parentId, menuName, type));
    }

    /**
     * 返回角色的菜单集合
     *
     * @param roleId 角色ID
     * @return 属性集合
     */
    @GetMapping(RestApiConfig.TREE + "/{roleId}")
    public R<List<Long>> getRoleTree(@PathVariable Long roleId) {
        return R.success(sysMenuService.findMenuByRoleId(roleId).stream().map(SysMenu::getMenuId).collect(Collectors.toList()));
    }

    /**
     * 同步菜单缓存
     */
    @LogAnnotation(title = "同步菜单缓存", operateType = OperateType.CLEAN)
    @PutMapping(RestApiConfig.SYNC)
    @PreAuthorize("@pms.hasPermission('sys_menu_del')")
    public R<?> sync() {
        sysMenuService.sync();
        return R.success();
    }
}
